package com.shop.front.service.user;

import com.shop.front.property.BusinessProps;
import com.shop.front.response.FrontRetEnum;
import com.shop.front.service.system.SystemService;
import com.shop.common.enums.System.NewSystemConfigEnum;
import com.shop.common.enums.TrueFalseEnum;
import com.shop.common.enums.user.BillTableNameEnum;
import com.shop.common.enums.user.IncomeTypeEnum;
import com.shop.common.partner.nameauth.IRealNameAuth;
import com.shop.domain.system.NewSystemConfig;
import com.shop.domain.user.User;
import com.shop.domain.user.UserRealNameAuth;
import com.shop.front.consts.FrontConst;
import com.shop.front.dao.realname.UserRealNameAuthDao;
import com.shop.front.dao.user.UserDao;
import com.shop.front.request.user.RealNameAuthReq;
import com.shop.front.util.tencent.IdCardVerification;
import com.shop.util.DateUtil;
import com.shop.web.cache.RedisCache;
import com.shop.web.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Slf4j
@Transactional
public class RealNameAuthService {

    @Autowired
    private UserRealNameAuthDao userRealNameAuthDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private IRealNameAuth realNameAuth;
    @Autowired
    private BusinessProps businessProps;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SystemService systemService;
    @Autowired
    private UserIntegtralBillService userIntegtralBillService;

    /**
     * 实名认证
     *
     * @param userId
     * @param req
     * @return
     */
    public BaseResponse auth(Long userId, String ip, RealNameAuthReq req) {
        // 实名认证缓存key
        int cacheTime = 3;  // 秒
        String cacheKey = "realname_auth_" + userId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            return BaseResponse.fail("操作过于频繁，请稍后重试！");
        } else {
            // 缓存请求
            redisCache.set(cacheKey, userId.toString(), cacheTime);
        }

        User user = userDao.findSingle(userId);
        if(StringUtils.isNotBlank(user.getRealName()) && StringUtils.isNotBlank(user.getCardId())) {
            return new BaseResponse(FrontRetEnum.USER_REAL_NAME_IS_AUTH);
        }

       /* if(!RegexUtils.isIdNumber(user.getCardId())){
            return BaseResponse.fail("请确认身份证号码是否填写正确！");
        }*/


        // 姓名+身份证是否已实名成功过
        String realName = req.getRealName();
        String idCard = req.getIdCard();


        //实名账号超限 不能继续实名
  /*      int authCardNum = userDao.queryAuthCardIdCount(realName,idCard);
        if(authCardNum > 31){//同一个身份证实名不能超过31个号
            return BaseResponse.fail("该身份信息实名用户数超限！");
        }*/

        int authSuccessCount = userRealNameAuthDao.countByAuthSuccess(realName, idCard);
        if(authSuccessCount <= 0) { // 未认证通过过
     /*       String todayStr = DateUtil.getTodayDate();

            // 同一个用户一天可实名次数
            int sendCount = userRealNameAuthDao.countByUidAndDate(userId, todayStr);
            if (sendCount >= FrontConst.REAL_NAME_AUTH_MOBILE_DAY_MAX_SEND_COUNT) {
                return new BaseResponse<>(FrontRetEnum.REAL_NAME_AUTH_MOBILE_SEND_EXCESS);
            }

            // 同一个ip一天可实名次数
            sendCount = userRealNameAuthDao.countByIpAndDate(ip, todayStr);
            if (sendCount >= FrontConst.REAL_NAME_AUTH_IP_DAY_MAX_SEND_COUNT) {
                return new BaseResponse<>(FrontRetEnum.REAL_NAME_AUTH_MOBILE_SEND_EXCESS);
            }

            // 非生产环境，直接通过
            if (!businessProps.isProEnv()) {
                return new BaseResponse();
            }*/

            // 信息入库
            UserRealNameAuth auth = new UserRealNameAuth();
            auth.setRealityName(realName);
            auth.setIdNumber(idCard);
            auth.setUid(userId);
            auth.setIp(ip);

            // 请求接口实名认证
            boolean authStatus = IdCardVerification.VerifyIdCard(idCard, realName);
            if(!authStatus) {
                auth.setIsSuccess(TrueFalseEnum.val(authStatus).getCode());
                userRealNameAuthDao.save(auth);
                return BaseResponse.fail("实名认证失败，请确认姓名与身份证号是否正确！");
            }

            auth.setIsSuccess(1);
            userRealNameAuthDao.save(auth);


          /*  User spreadUser = userDao.findSingle(user.getSpreadUid());

            if(null != spreadUser){

                //第一次实名 给推荐人积分
                NewSystemConfig newSystemConfig = systemService.getSystemConfig(NewSystemConfigEnum.AUTH_SUCCESS_SEND_SPREAD_INGEGRAL);
                BigDecimal sendIngegral = new BigDecimal(newSystemConfig.getValue());
                userDao.addIntegral(spreadUser.getId(),sendIngegral);

                //添加增加积分获得记录
                BigDecimal refreshIntegral = spreadUser.getIntegral().add(sendIngegral);
                userIntegtralBillService.addUserIntegralBill(spreadUser.getId(), auth.getId(), spreadUser.getIntegral(),sendIngegral,refreshIntegral,
                        BillTableNameEnum.AUTH_SUCCESS_SEND_SPREAD_INGEGRAL.getKey(), IncomeTypeEnum.INCOME.getKey(),  "用户实名，推荐人获得积分" + sendIngegral);
            }*/

        }

        // 修改实名信息
        userDao.updateIdCardAndRealName(userId, idCard, realName);

        return new BaseResponse();
    }
}
